<template>
	<div class="ml-auto">
		<n-popover
			trigger="click"
			placement="bottom-end"
			:show-arrow="false"
			:show="showHot"
			@update:show="handleUpdateShowHot">
			<template #trigger>
				<div
					class="h-[40px] p-4 rounded-lg bg-bg-3 flex items-center app-bg-react text-t-2 cursor-pointer">
					<base-icon
						name="filter"
						size="16"
						color="var(--color-text-3)"
						class="mr-2 duration-300" />
					{{ selectedMenuItemName || $t('action.sort.popular') }}
				</div>
			</template>
			<div class="w-[131px] bg-gray-800 text-white rounded-md overflow-hidden shadow-lg">
				<ul class="flex flex-col">
					<li
						v-for="item in menuItems"
						:key="item.id"
						:class="{
							'text-purple-400': selectedMenuItem === item.id,
							'hover:bg-gray-700': true
						}"
						class="px-4 py-2 cursor-pointer"
						@click="selectMenuItem(item.id)">
						{{ item.name }}
					</li>
				</ul>
			</div>
		</n-popover>
	</div>
</template>

<script lang="ts" setup>
import { computed, ref, defineEmits, watch } from 'vue'
import { BaseIcon } from '@/components/base'
import { NPopover } from 'naive-ui'
import { t } from '@/utils'

const emit = defineEmits(['update-sorting-values'])
const props = defineProps({
	tagData: {
		type: Object,
		default: () => ({
			id: '',
			gameTagGroupId: ''
		})
	}
})
// 控制“热门”菜单的弹出状态
const showHot = ref(false)
// selectedMenuItem 用于管理选中的菜单项的 ID
const selectedMenuItem = ref<number | null>(1)

// 计算属性，用于显示选中项的名称
const selectedMenuItemName = computed(() => {
	const selectedItem = menuItems.value.find((item) => item.id === selectedMenuItem.value)
	return selectedItem ? selectedItem.name : null
})

// 选择菜单项时，保存选择并关闭菜单
const selectMenuItem = (id: number) => {
	const selectedItem = menuItems.value.find((item) => item.id === id)
	if (selectedItem) {
		selectedMenuItem.value = selectedItem.id
	}
	showHot.value = false
	emit('update-sorting-values', id)
}

// 动态获取热门菜单项
const menuItems = computed(() => [
	{ id: 1, name: t('action.sort.recommend') },
	{ id: 2, name: t('action.sort.popular') },
	{ id: 5, name: t('action.sort.random') },
	{ id: 3, name: 'A-Z' },
	{ id: 4, name: 'Z-A' }
])

watch(
	() => props.tagData,
	() => {
		//selectedMenuItem.value = 1
	}
)
// 更新“热门”菜单的显示状态
const handleUpdateShowHot = (val: boolean) => {
	showHot.value = val
}
</script>
